package com.zl.csMall.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.net.NetworkInterface;
import java.util.*;

/**
 * @description: SecretUtil
 * @author: ChenNing
 * @date 2025-03-11 15:38
 */
public class SecretUtil {
    private static final String ALGORITHM = "AES";

    // 生成密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(128); // AES supports 128, 192, or 256 bits
        return keyGen.generateKey();
    }

    // 将密钥转换为字符串以便存储或传输
    public static String keyToString(SecretKey secretKey) {
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    // 从字符串还原密钥
    public static SecretKey stringToKey(String keyStr) {
        byte[] decodedKey = Base64.getDecoder().decode(keyStr);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM);
    }

    // 加密数据
    public static String encrypt(String data, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密数据
    public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }

    /**
     * @description: 获取本机MAC
     * @author ChenNing
     * @date: 2025-09-26 17:03
     */
    public static String getServerMac() throws Exception {
        // 获取本地主机的所有网络接口
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            // 过滤条件：非虚拟接口、非回环地址、已启用且有物理地址
            if (!ni.isVirtual() && !ni.isLoopback() && ni.isUp()) {
                byte[] hardwareAddress = ni.getHardwareAddress();
                if (hardwareAddress != null && hardwareAddress.length > 0) {
                    // 将字节数组转换为标准MAC格式（XX:XX:XX:XX:XX:XX）
                    StringBuilder macBuilder = new StringBuilder();
                    for (int i = 0; i < hardwareAddress.length; i++) {
                        if (i > 0) {
                            macBuilder.append(":");
                        }
                        String hexByte = Integer.toHexString(hardwareAddress[i] & 0xFF);
                        if (hexByte.length() == 1) {
                            macBuilder.append('0'); // 补零保证两位数格式
                        }
                        macBuilder.append(hexByte.toUpperCase());
                    }
                    return macBuilder.toString();
                }
            }
        }
        throw new IllegalArgumentException("未找到有效的MAC地址！");
    }

    /**
     * @description: 获取本机MAC集合（该网络下全部MAC）
     * @author ChenNing
     * @date: 2025/4/8 16:28
     */
    public static List<String> getServerMacList() {
        List<String> list = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Optional.ofNullable(networkInterface.getHardwareAddress())
                        .ifPresent(mac -> list.add(format(mac)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 将 mac 字节数组格式化为全大写并且使用 - 作为分隔符的字符串
     * @param mac 获取到的 mac 字节数组
     * @return 格式化后的 mac 地址
     */
    private static String format(byte[] mac) {
        StringBuilder sb = new StringBuilder();
        for (byte b : mac) {
            sb.append(String.format("%02X", b)).append("-");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    
}
